package com.chen.positioning.recharge.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.chen.positioning.amountconfig.entity.AmountConfig;
import com.chen.positioning.config.pay.AlipayConfig;
import com.chen.positioning.config.pay.AntPayConfig;
import com.chen.positioning.recharge.service.RechargeRecordService;
import com.chen.positioning.util.CommonJsonReturnMessage;
import com.chen.positioning.util.DateUtils;
import org.apache.tools.ant.taskdefs.Ant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author halo
 * @create 2019-08-24 11:15
 */
@Controller
@RequestMapping("/rechargeRecord")
public class RechargeRecordController {

    private static final Logger logger = LoggerFactory.getLogger(RechargeRecordController.class);

    @Autowired
    RechargeRecordService rechargeService;
    @Autowired
    CommonJsonReturnMessage commonJsonReturnMessage;

    /**
     * 充值包月初始页面
     *
     * @return
     */

    @RequestMapping(value = "/recharge_monthly", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ModelAndView phonePositioning(HttpSession session,String phoneNum) {
        logger.info("已进入充值包月初始页面....");
        List<AmountConfig> amountConfigList = new ArrayList<AmountConfig>();
        ModelAndView modelAndView = new ModelAndView();//实例化一个View的ModelAndView对象
        try {
            amountConfigList = rechargeService.findAmountConfigInfo();
            logger.info("充值包月初始页面[" + amountConfigList.get(0).toString() + "]");
            session.setAttribute("amountConfig", amountConfigList.get(0));
            modelAndView.setViewName("onlineRecharge");//转发到games.html
            //封装数据，用于前端页面渲染，这里我返回的是一个List。当然Map，Set等数据结构也是可以的。
            modelAndView.addObject("rechargeConfig", amountConfigList.get(0));
            modelAndView.addObject("phoneNum",phoneNum);
            return modelAndView;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("recharge_monthly error." + e);
            return modelAndView;
        }
    }
    /*@RequestMapping(value = "/goRecharge", method = {RequestMethod.POST, RequestMethod.GET})
    public String goRecharge() {
        logger.info("goRecharge....");
        return "onlineRecharge";
    }*/

    /**
     * 充值业务类
     *
     * @param session
     * @param response
     * @param cost
     * @return
     */
    @RequestMapping(value = "/choose_recharge", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView viewMap(HttpSession session, HttpServletResponse response, int cost) {
        ModelAndView modelAndView = new ModelAndView();//实例化一个View的ModelAndView对象
        logger.info("需要支付的金额是:" + cost);
        try {
            if (cost > 0) {
                AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

                //设置请求参数
                AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
                alipayRequest.setReturnUrl(AlipayConfig.return_url);
                alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
                //商户订单号，商户网站订单系统中唯一订单号，必填  使用时间戳作为订单号
                String out_trade_no = DateUtils.parseDateToStr(DateUtils.YYYYMMDDHHMMSS, new Date());
                System.out.println("out_trade_no="+out_trade_no);
                //付款金额，必填
                String total_amount = Integer.toString(cost);

                //订单名称，必填
                String subject ="recharge";

                //商品描述，可空
                String body = "buy something";

                alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                        + "\"total_amount\":\""+ total_amount +"\","
                        + "\"subject\":\""+ subject +"\","
                        + "\"body\":\""+ body +"\","
                        + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

                String result = alipayClient.pageExecute(alipayRequest).getBody();
                System.out.println(result);

                modelAndView.addObject("result",result);
                //随意进入一个页面 系统将自动转入到支付宝的平台
                modelAndView.setViewName("toPay");


            } else {
                modelAndView.setViewName("error");

            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("充值出错了", e);
            modelAndView.setViewName("error");
        }

        return modelAndView;

    }


    @PostMapping("/recharge_success")
    public String rechargeSuccess(){
        return "main";
    }

}
